from fastapi import APIRouter, UploadFile, File, HTTPException, status
from typing import List
import os
import aiofiles
import uuid
from pathlib import Path
import sys

# Add parent directories to path
sys.path.append(str(Path(__file__).parent.parent.parent))

from config.settings import settings
from src.models.base import BaseResponse, FileUploadResponse
from src.utils.file_parser import FileParser
from src.utils.logger import get_logger

router = APIRouter(prefix="/api/v1/files", tags=["文件处理"])
logger = get_logger(__name__)
file_parser = FileParser()


@router.post("/upload", response_model=FileUploadResponse)
async def upload_file(file: UploadFile = File(...)):
    """上传文件并解析为文本."""
    
    # 验证文件类型
    if file.content_type not in settings.allowed_file_types:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"不支持的文件类型: {file.content_type}"
        )
    
    # 验证文件大小
    if hasattr(file, 'size') and file.size > settings.max_file_size:
        raise HTTPException(
            status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
            detail=f"文件大小超出限制 ({settings.max_file_size // (1024*1024)}MB)"
        )
    
    try:
        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = Path(settings.upload_path) / unique_filename
        
        # 确保上传目录存在
        file_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 保存文件
        async with aiofiles.open(file_path, 'wb') as f:
            content = await file.read()
            await f.write(content)
        
        file_size = len(content)
        logger.info(f"文件上传成功: {unique_filename}, 大小: {file_size}")
        
        # 解析文件内容
        try:
            extracted_text = await file_parser.parse_file(file_path, file.content_type)
        except Exception as e:
            logger.warning(f"文件解析失败，但文件已保存: {str(e)}")
            extracted_text = None
        
        return FileUploadResponse(
            success=True,
            message="文件上传和解析成功",
            filename=unique_filename,
            file_size=file_size,
            file_type=file.content_type,
            extracted_text=extracted_text
        )
        
    except Exception as e:
        logger.error(f"文件上传失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件上传失败: {str(e)}"
        )


@router.post("/parse", response_model=BaseResponse)
async def parse_file_by_path(file_path: str):
    """通过文件路径解析文件."""
    
    try:
        path = Path(file_path)
        if not path.exists():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="文件不存在"
            )
        
        extracted_text = await file_parser.parse_file(path)
        
        return BaseResponse(
            success=True,
            message="文件解析成功",
            data={
                "file_path": str(path),
                "extracted_text": extracted_text,
                "text_length": len(extracted_text)
            }
        )
        
    except Exception as e:
        logger.error(f"文件解析失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件解析失败: {str(e)}"
        )


@router.get("/supported-types")
async def get_supported_file_types():
    """获取支持的文件类型列表."""
    return BaseResponse(
        success=True,
        message="获取支持的文件类型成功",
        data={
            "supported_types": list(file_parser.SUPPORTED_TYPES.keys()),
            "allowed_types": settings.allowed_file_types,
            "max_file_size_mb": settings.max_file_size // (1024 * 1024)
        }
    )